<template>
  <div class="websites-tab">
    <div class="current-website-control">
      <div class="control-header">
        <h2>当前网站拦截控制</h2>
        <div class="current-url">{{ currentDomain }}</div>
      </div>

      <div class="control-switch">
        <label class="switch">
          <input
            type="checkbox"
            :checked="isCurrentEnabled"
            @change="toggleCurrentWebsite"
          >
          <span class="slider"></span>
        </label>
        <div class="switch-label">
          <div class="switch-title">{{ isCurrentEnabled ? '拦截已启用' : '拦截已禁用' }}</div>
          <div class="switch-desc">
            {{ isCurrentEnabled ? '当前网站会显示悬浮按钮' : '当前网站不会显示悬浮按钮' }}
          </div>
        </div>
      </div>
    </div>

    <div class="help-section">
      <div class="help-title">💡 使用说明</div>
      <div class="help-content">
        <p>• 启用拦截后，当前网站会显示悬浮按钮</p>
        <p>• 通过悬浮按钮可以管理请求拦截规则</p>
        <p>• 禁用后不会显示任何拦截功能</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useInterceptorStore } from '@/stores/interceptor'

const store = useInterceptorStore()

// 直接操作localStorage的工具函数
const saveToLocalStorage = (websites) => {
  try {
    console.log('🔄 准备保存到localStorage:', websites)
    localStorage.setItem('enabled_websites', JSON.stringify(websites))

    // 立即验证是否保存成功
    const saved = localStorage.getItem('enabled_websites')
    console.log('✅ 保存后立即读取验证:', saved)

    if (saved) {
      console.log('✅ localStorage保存成功!')
    } else {
      console.error('❌ localStorage保存失败 - 读取为空')
    }
  } catch (error) {
    console.error('❌ 保存到localStorage失败:', error)
  }
}

const getFromLocalStorage = () => {
  try {
    const stored = localStorage.getItem('enabled_websites')
    console.log('📖 从localStorage读取原始数据:', stored)
    const result = stored ? JSON.parse(stored) : []
    console.log('📖 解析后的数据:', result)
    return result
  } catch (error) {
    console.error('❌ 从localStorage读取失败:', error)
    return []
  }
}

// 当前网站域名
const currentDomain = ref('获取中...')
// 当前网站是否启用拦截
const isCurrentEnabled = ref(false)

// 获取当前标签页域名
const getCurrentTabDomain = async () => {
  try {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true })
    if (tab && tab.url) {
      return new URL(tab.url).hostname
    }
    return 'unknown'
  } catch (error) {
    console.error('获取当前标签页失败:', error)
    return 'unknown'
  }
}

// 初始化数据
const initializeData = async () => {
  // 1. 先获取当前域名
  const domain = await getCurrentTabDomain()
  currentDomain.value = domain
  console.log('🌐 当前域名:', domain)

  // 2. 读取localStorage中的数据
  const enabledList = getFromLocalStorage()
  console.log('📋 localStorage中的启用列表:', enabledList)

  // 3. 判断当前网站是否在启用列表中
  const enabled = enabledList.includes(domain)
  isCurrentEnabled.value = enabled
  console.log('🎯 当前网站拦截状态:', enabled)

  // 4. 同步到store (保持一致性)
  store.enabledWebsites.value = enabledList
}

onMounted(() => {
  initializeData()
})

// 切换当前网站状态
const toggleCurrentWebsite = () => {
  const domain = currentDomain.value
  console.log('🔄 开始切换网站状态 - 域名:', domain)

  if (domain === 'unknown' || domain === '获取中...') {
    console.log('❌ 域名无效，无法切换:', domain)
    return
  }

  console.log('� 切换前的状态:')
  console.log('  - 当前域名:', domain)
  console.log('  - 当前开关状态:', isCurrentEnabled.value)

  // 读取当前localStorage数据
  const currentList = getFromLocalStorage()

  const wasEnabled = isCurrentEnabled.value
  let newList

  if (wasEnabled) {
    // 移除网站
    newList = currentList.filter(site => site !== domain)
    console.log(`➖ 准备移除网站 ${domain}`)
    console.log('  - 移除前列表:', currentList)
    console.log('  - 移除后列表:', newList)
  } else {
    // 添加网站
    newList = [...currentList, domain]
    console.log(`➕ 准备添加网站 ${domain}`)
    console.log('  - 添加前列表:', currentList)
    console.log('  - 添加后列表:', newList)
  }

  // 保存到localStorage
  console.log('💾 开始保存到localStorage...')
  saveToLocalStorage(newList)

  // 更新本地状态
  isCurrentEnabled.value = !wasEnabled
  console.log('🔄 已更新本地开关状态为:', isCurrentEnabled.value)

  // 同时更新store (保持同步)
  store.enabledWebsites.value = newList
  console.log('🔄 已同步到store:', store.enabledWebsites.value)

  // 通知content script更新状态
  const newEnabled = !wasEnabled
  console.log('📤 准备发送消息给content script:', { domain, enabled: newEnabled })

  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    if (tabs[0]) {
      console.log('📤 发送消息到标签页:', tabs[0].id)
      chrome.tabs.sendMessage(tabs[0].id, {
        type: 'WEBSITE_STATUS_CHANGED',
        domain: domain,
        enabled: newEnabled
      }).then(() => {
        console.log('✅ 消息发送成功')
      }).catch(error => {
        console.log('❌ 消息发送失败:', error)
      })
    } else {
      console.log('❌ 没有找到活动标签页')
    }
  })

  console.log('🎉 切换操作完成!')
}
</script>

<style scoped>
.websites-tab {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
}

.current-website-control {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 24px;
}

.control-header {
  margin-bottom: 24px;
  text-align: center;
}

.control-header h2 {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
}

.current-url {
  font-family: 'JetBrains Mono', 'Fira Code', 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 14px;
  color: #6b7280;
  background: #f3f4f6;
  padding: 8px 12px;
  border-radius: 6px;
  display: inline-block;
}

.control-switch {
  display: flex;
  align-items: center;
  gap: 16px;
}

.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: .4s;
  border-radius: 34px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  transition: .4s;
  border-radius: 50%;
}

input:checked + .slider {
  background-color: #4ade80;
}

input:checked + .slider:before {
  transform: translateX(26px);
}

.switch-label {
  flex: 1;
}

.switch-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 4px;
}

.switch-desc {
  font-size: 14px;
  color: #6b7280;
}



.help-section {
  background: #fef3c7;
  border: 1px solid #fbbf24;
  border-radius: 8px;
  padding: 16px;
}

.help-title {
  font-size: 14px;
  font-weight: 600;
  color: #92400e;
  margin-bottom: 8px;
}

.help-content p {
  margin: 4px 0;
  font-size: 13px;
  color: #92400e;
}
</style>
